﻿using CatUtils.Utils.Currency;
using CatUtils.Utils.Currency.TextUtils;

using CatUtils.Utils.SpecialUtils.Html;
using CatUtils.Utils.SpecialUtils.View;
using CatUtilsDll.Utils.Currency.WebUtils;
using Newtonsoft.Json;
using RabbitDownload.Helper;
using RabbitDownload.Helper.Currency;

using System;
using System.Collections.Generic;
using static RabbitDownload.WebSite.Local.TagManger.LocalTagStatcivalue;

namespace RabbitDownload.WebSite.Pixiv.PixivTagMember
{
    internal class PTMStartScanner
    {
        /// <summary>
        /// 加载词库文件运行批量扫描
        /// </summary>
        /// <param name="ListFilePath"></param>
        /// <param name="StartPage"></param>
        /// <param name="EndPage"></param>
        /// <param name="Score"></param>
        /// <param name="Count"></param>
        public void StartBatch(string ListFilePath, string StartPage, string EndPage, string Score, string Count, CWebclient cWebclient)
        {
            List<string> TagInfoList = new SiteCurrencyHelper().GetDownoadProcess(ListFilePath, "//item");
            int CompltedCount = 0;
            int ALLImgCount = TagInfoList.Count;
            while (TagInfoList.Count > 0)
            {
                string TagInfo = TagInfoList[0];
                new PrintLog().PercentLog(ALLImgCount, ++CompltedCount);
                TagInfoList.RemoveAt(0);
                new SiteCurrencyHelper().SaveDownloadProcess(ListFilePath, TagInfoList);
                TranslateStruct translateStruct = new TranslateStruct(TagInfo);

                if (translateStruct.JpTag == "")
                {
                    Console.WriteLine("日文标签为空，以下是代码：\r\n" + TagInfo);
                    continue;
                }

                Console.WriteLine("扫描标签{0}，日语标签{1}", translateStruct.ZhTag, translateStruct.JpTag);
                if (translateStruct.ZhTag == "" || translateStruct.JpTag == "")
                    continue;
                List<string> TempList = new PTMStartScanner().ScannerSingle(translateStruct.JpTag, StartPage, EndPage, Score, Count, cWebclient);

                string FileName = "";
                if (translateStruct.ZhtwTag != "")
                    FileName = string.Format("中文：{0}繁体中文：{1}日文：{2}", translateStruct.ZhTag, translateStruct.ZhtwTag, translateStruct.JpTag);
                else
                    FileName = string.Format("中文：{0}日文：{1}", translateStruct.ZhTag, translateStruct.JpTag);
                WebCurrency.SaveHelper.AutoSave(TempList, "P站标签", FileName);
            }
        }

        /// <summary>
        /// 初始化扫描
        /// </summary>
        /// <param name="Tag"></param>
        /// <param name="StartPage"></param>
        /// <param name="EndPage"></param>
        /// <param name="Score"></param>
        /// <param name="Count"></param>
        public void InitStart(string Tag, string StartPage, string EndPage, string Score, string Count, CWebclient cWebclient)
        {
            List<string> TempList = new PTMStartScanner().ScannerSingle(Tag, StartPage, EndPage, Score, Count, cWebclient);
            WebCurrency.SaveHelper.AutoSave(TempList, "P站标签", Tag);
        }

        /// <summary>
        /// 获取单个结果，并且处理
        /// </summary>
        /// <param name="Tag"></param>
        /// <param name="StartPage"></param>
        /// <param name="EndPage"></param>
        /// <param name="Score"></param>
        /// <param name="Count"></param>
        /// <returns></returns>
        public List<string> ScannerSingle(string Tag, string StartPage, string EndPage, string Score, string Count, CWebclient cWebclient)
        {
            int StartpageInt = TextHelper.StringToInt(StartPage);
            int EndpageInt = TextHelper.StringToInt(EndPage);
            int ScoreInt = TextHelper.StringToInt(Score);
            int DownloadCount = TextHelper.StringToInt(Count);

            return new PTMStartScanner().LocalScanner(StartpageInt, EndpageInt, ScoreInt, DownloadCount, Tag, cWebclient);
        }

        /// <summary>
        /// 启动本地扫描
        /// </summary>
        /// <param name="StartPage"></param>
        /// <param name="EndPage"></param>
        /// <param name="ScoreInt"></param>
        /// <param name="DownloadCount"></param>
        /// <param name="Tag"></param>
        private List<string> LocalScanner(int StartPage, int EndPage, int ScoreInt, int DownloadCount, string Tag, CWebclient cWebclient)
        {
            if (StartPage <= 0)
            {
                StartPage = 1;
            }
            if (EndPage != 0 && StartPage > EndPage)
            {
                MessageHelper.Alert("起始页不能大于结束页！");
                return new List<string>();
            }
            if (EndPage == 0)
                EndPage = 5000;
            string API = "";
            if (PixMemStaticvlaue.MemberFlag)
                API = string.Format(PixMemStaticvlaue.SearchIndexForMember, WebHelper.UrlEncode(Tag), "{0}");
            else
                API = string.Format(PixMemStaticvlaue.SearchIndex, WebHelper.UrlEncode(Tag), "{0}");

            List<string> TempList = new List<string>();
            int JumpNullCount = 0;
            int JumpRepeatCount = 0;
            for (int i = StartPage; i <= EndPage; i++)
            {
                List<string> ImgListTemp = AnalysisAPI(string.Format(API, i), ScoreInt, DownloadCount - TempList.Count, cWebclient);

                if (ImgListTemp != null)
                {
                    foreach (var item in ImgListTemp)
                    {
                        if (TempList.Contains(item))

                        {
                            PrintLog.INoWrite(string.Format("检测到图片出现重复{0}次。距离跳出还有：{1}次。", JumpRepeatCount++, 120 - JumpRepeatCount));
                            if (JumpRepeatCount >= 120)
                                return TempList;
                        }
                        else
                            TempList.Add(item);
                    }
                }

                if (ImgListTemp == null || ImgListTemp.Count == 0)
                {
                    JumpNullCount++;
                    if (JumpNullCount >= 5)
                    {
                        PrintLog.ENoWrite(string.Format("连续未解析到合格图片：{0}次。距离跳出还有：{1}次。", JumpNullCount++, 5 - JumpNullCount));
                        return ImgListTemp;
                    }
                }

                Console.WriteLine("合格图片{0}张", TempList.Count);
                if (DownloadCount != 0 && (DownloadCount - TempList.Count) <= 0)
                {
                    Console.WriteLine("flag1达到预设数量，跳出！");
                    break;
                }
            }
            return TempList;
        }

        /// <summary>
        /// 分析页面获得结果。
        /// </summary>
        /// <param name="API"></param>
        /// <returns></returns>
        private List<string> AnalysisAPI(string API, int ScoreInt, int DownloadCount, CWebclient cWebclient)
        {
            Console.WriteLine("分析：{0}", API);
            List<string> ImgListTemp = new List<string>();
            String Shtml = cWebclient.GetHtml(API, WebHelper.PcWebHeader());

            String GetJson = HtmlHelper.GetFirstAttributes(Shtml, "data-items", "//input[@id='js-mount-point-search-result-list']").Replace("&quot;", "\"");

            GetJson = TextHelper.ReplaceTextEnhance(GetJson, ",\"illustSeries\":\\{.*?\"\\}", "");

            if (GetJson.Length < 10)
            {
                Console.WriteLine("获取不到更多资源，结束扫描");
                return ImgListTemp;
            }
            //由于返回结果不规范，先用正则进行一次校对
            List<string> JsonItemList = TextHelper.RegexTextList(GetJson, "{\"illustId\":.*?bookmarkCount[\\w\\W]{0,10},\"responseCount\":[0-9]{1,}}");

            foreach (string line in JsonItemList)
            {
                List<string> TempImglist = AnalysisJson(line, ScoreInt);
                if (TempImglist == null)
                    continue;
                if (TempImglist.Count > 0)
                {
                    ImgListTemp.AddRange(TempImglist);
                }

                if (DownloadCount > 0)
                {
                    int PedingCount = DownloadCount - ImgListTemp.Count;
                    Console.WriteLine("二级缓存扫描{0}张，还需要下载{1}张。", ImgListTemp.Count, PedingCount);
                    if (PedingCount <= 0)
                    {
                        Console.WriteLine("达到用户预设数量，跳出！");
                        return ImgListTemp;
                    }
                }
            }

            return ImgListTemp;
        }

        /// <summary>
        /// 分析JSON
        /// </summary>
        /// <param name="line"></param>
        /// <returns></returns>
        private List<string> AnalysisJson(string line, int ScoreInt)
        {
            List<string> ImgListTemp = new List<string>();

            try
            {
                PixMemStaticvlaue.PixivItem.Root ImgItem = JsonConvert.DeserializeObject<PixMemStaticvlaue.PixivItem.Root>(line);
                if (ScoreInt != 0 && ImgItem.bookmarkCount < ScoreInt)
                {
                    Console.WriteLine("评分:{0}过低，跳过。", ImgItem.bookmarkCount);
                    return null;
                }

                if (PixMemStaticvlaue.BlockComicEnhance && (ContrastWidthAndHeight(ImgItem.width, ImgItem.height) || ImgItem.pageCount > 1))
                {
                    PrintLog.DNoWrite(string.Format("通过宽高比判断漫画，图片宽度{0} 高度{1},该图集图片数量{2}，ID：{3}", ImgItem.width, ImgItem.height, ImgItem.pageCount, ImgItem.illustId));
                    return ImgListTemp;
                }
                PrintLog.DNoWrite(string.Format("图片数量：{0}图片类型{1}，图片收藏数{2}，ID：{3}", ImgItem.pageCount, ImgItem.illustType, ImgItem.bookmarkCount, ImgItem.illustId));
                ImgListTemp.AddRange(GetImgLink(ImgItem, ImgItem.bookmarkCount));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            return ImgListTemp;
        }

        /// <summary>
        /// 判断是否需要跳过 需要跳过返回true;
        /// </summary>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <returns></returns>
        private bool ContrastWidthAndHeight(int width, int height)
        {
            float Proportion = (float)width / height;
            if (Proportion < 0.3 || Proportion > 2)
            {
                Console.WriteLine("宽{0}高{1}比例{2}错误，跳过", width, height, Proportion);
                return true;
            }

            return false;
        }

        /// <summary>
        /// 获取图片链接
        /// </summary>
        /// <param name="ImgItem"></param>
        /// <param name="Score"></param>
        /// <returns></returns>
        private List<string> GetImgLink(PixMemStaticvlaue.PixivItem.Root ImgItem, int Score)
        {
            List<string> ListTemp = new List<string>();
            if (PixivStaticValue.ExcludeOpenFlag &&
                (ListHelper.CompareRepetition(ImgItem.tags, StaticValueOld.ExcludeList) ||//判断标签合规和用户ID合规
                 ListHelper.CompareRepetition(new List<string>() { ImgItem.userId }, StaticValueOld.ExcludeList))
                )
            {
                Console.WriteLine("检测到不合规定关键词，跳出");
                return ListTemp;
            }

            if (ImgItem.illustType == 2)
            {
                Console.WriteLine("检测到Pixiv动图。");
                ListTemp.Add(new PixivHelper().AnalysisGIF(ImgItem.url, ImgItem.illustId, Score.ToString()));
            }
            else
            {
                //  Console.WriteLine("Pixiv普通图。");
                ListTemp.AddRange(new PixivHelper().QuickAnalysisAllImg(ImgItem.pageCount, ImgItem.url, ImgItem.illustId, Score.ToString()));
            }

            return ListTemp;
        }
    }
}